package com.yyge.util.easyexcel.convert;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.FileUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author wy
 * @Description url转换成二进制，二进制流转换excel image
 * @Date 2023/4/15 17:45
 * @Version 1.0
 */
@Log4j2
public class UrlToImageConverter implements Converter<String> {

    public UrlToImageConverter() {
    }

    public Class<?> UrlToImageConverter() {
        return String.class;
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        // value --> http 请求 --> InputStream-->写入到 byteInputStream-->toArray[]
        //https://waimai-1300180953.cos.ap-chongqing.myqcloud.com/images/e12b31ba-97fe-4066-9d80-9c5de5d3d830.png
        // get请求 --> 流 --> byte[]
        if(StrUtil.isBlank(value)){
            return new WriteCellData<>("没有图片");
        }

        // spring框架封装的http请求库(get,post,put,delete请求)
        HttpComponentsClientHttpRequestFactory requestFactory=new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectionRequestTimeout(3000);
        requestFactory.setConnectTimeout(3000);
        requestFactory.setReadTimeout(3000);
        RestTemplate restTemplate=new RestTemplate(requestFactory);

        //返回结果为byte[]
        try {
            ResponseEntity<byte[]> forEntity = restTemplate.getForEntity(value, byte[].class);
            //图片 访问OK
            if (forEntity.getStatusCode() == HttpStatus.OK) {
                byte[] body = forEntity.getBody();
                //写入图片
                return new WriteCellData<>(body);
            } else {
                return new WriteCellData<>("图片访问失败");
            }
        }catch(Exception e){
            //记录日志
            log.error(e);
            return new WriteCellData<>("图片访问失败");
        }
    }
}
